package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.constant.MessageConstant;
import com.atguigu.entity.Result;
import com.atguigu.pojo.Member;
import com.atguigu.service.MemberService;
import com.atguigu.utils.RedisMessageConstant;
import org.apache.poi.hpsf.ReadingNotSupportedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * LoginController
 *
 * @Author: 马伟奇
 * @CreateTime: 2021-02-03
 * @Description:
 */
@RequestMapping("/login")
@RestController
public class LoginController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @RequestMapping("/check")
    public Result check(@RequestBody Map map, HttpServletResponse response){
        // 获取用户输入的手机号码
        String telephone = (String) map.get("telephone");
        // 获取用户输入的验证码
        String validateCode = (String) map.get("validateCode");


        // 获取用户存在redis里面的验证码
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);

        // 判断用户输入的验证码是否错误
        if (codeInRedis == null || !validateCode.equals(codeInRedis)){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        Member member =  memberService.findByTelephone(telephone);
        // 判断是否是会员
        if (member == null){
            // 注册成会员
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.add(member);
        }
        // 创建cookie对象
        Cookie cookie = new Cookie("login_member_telephone",telephone);
        cookie.setPath("/");//路径
        cookie.setMaxAge(60*60*24*30);//有效期30天（单位秒）
        response.addCookie(cookie);
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}